# In this script we will simulate the claim number and claim severity of a
# workers compensation portfolio with 1000 policies over the course of one year.
# The policy contract specifies that the maximum indemnity for each claim is
# 1,5 million.

# We assume that the number of claims of each policy follows a Poisson distribution.
# By the Central Limit Theorem, we may assume that the number of claims of all
# policies follows a Normal distribution.

# We first assume that the claim severity follows a Lognormal distribution.
# Alternatively, we can also resample from the original observed claim severities.

###################### Assumptions ########################

# Number of policies
n.policies <- 1000
n.policies

# Claim frequency theta (probability of a claim in a specific policy over the 
# course of one year)
mean.theta <- 0.1
mean.theta
sd.theta <- .02
sd.theta

# Lognormal severity parameters
source("9.1.Lognormal fit to a set of claims.R")
lognorm$mu
lognorm$sigma

# Maximum indemnity per claim
max <- 1500000

# Expenses and premiums: gross loading and expenses
gross.load <- 0.25
expense <- 0.2

# Quota share: Retention, ceding commission, loss corridor from claims ratio and 
# loss corridor to claims ratio (120% xs 180%)
retention <- .5
commission <- .2
lc.from.cr <- 1.2
lc.to.cr <- 1.8
retention
commission
lc.from.cr
lc.to.cr

# Excess of loss: Priority, limit, loading
priority <-  100000
priority
limit <- 400000  
limit
loading <- 0.25 # The XL reinsurance premium will be (1 + loading) * (mean of XL claims)
loading 

# Confidence level
cl <- .95
cl

# Number of simulations
n.sim <- 1500
n.sim


##################### Gross Claim Simulation #######################

# We start with a single column with the simulation numbers
gross.claims.sim <- tibble(sim = 1:n.sim)
gross.claims.sim

# Expected value and standard dev. for the total expected number of claims
N.mean.expect <- mean.theta * n.policies
N.mean.sd <- sd.theta * n.policies
N.mean.expect
N.mean.sd

# Simulate the expected number of claims
gross.claims.sim <- gross.claims.sim %>% 
  mutate(
    # Simulated expected number of claims (Central Limit Theorem)
    N.mean = N.mean.expect + N.mean.sd * rnorm(runif(n = n.sim)),
    # Simulated actual number of claims (sqrt(N.mean) is an assumption)
    N = N.mean + sqrt(N.mean) * rnorm(runif(n = n.sim))
  ) %>% 
  # There is a small probability that these simulated values are negative. That
  # cannot happen, of course.
  mutate(
    N.mean = if_else(N.mean < 0, 0, N.mean), 
    # Also, this one has to be an integer
    N = round(if_else(N < 0, 0, N))
  )
gross.claims.sim

# For each simulation, we have to simulate N claim severities. Here is where we use the
# lognormal distribution fitted in script `9.1.Lognormal fit to a set of claims.R`.
# The fastest way to do that is to use a "for loop" across all simulations.

n.sim
list.severities <- vector(mode = "list", length = n.sim)
for (i in seq_along(list.severities)){
  
  N <- gross.claims.sim %>% slice(i) %>% pull(N)
  list.severities[[i]] <- tibble(sim = i, claim = 1:N) %>% 
    
    # Introduce the lognormal severity using its relation to Normal distribution
    mutate(severity = exp(lognorm$mu + lognorm$sigma * rnorm(runif(n = N)))) %>%
    
    # # Another way to introduce the lognormal severity
    # mutate(qlnorm(runif(n = N), meanlog = lognorm$mu, sdlog = lognorm$sigma)) %>% 
    
    # # ALTERNATIVE 1 TO LOGNORMAL SEVERITY - Introduce gamma severity
    # mutate(severity = qgamma(runif(n = N), shape = 0.785, scale = 172655)) %>%
    
    # # ALTERNATIVE 2 TO LOGNORMAL SEVERITY - instead of using the lognormal distribution
    # # we can use resampling of the original claim values
    # mutate(severity = sample(claims$claims, N)) %>%

    # There is a maximum severity of 1,5M in the policy contract
    mutate(severity = if_else(severity < 1.5e6, severity, 1.5e6))
    
}

# Let's check some of the results to see that everything went as expected
list.severities[[5]]
list.severities[[643]]

# Data frame with claim severity of each individual claim, for every simulation
claims.sim.severities <- bind_rows(list.severities)
claims.sim.severities

# Calculate the simulated gross aggregated claims, i.e., the total severity in that
# year for each simulation. We want to add it to our initial table `gross.claims.sim`
temp <- claims.sim.severities %>%
  group_by(sim) %>% 
  summarize(gross.claims = sum(severity))
temp

# Join the simulated gross aggregated claims to our simulation data
gross.claims.sim <- gross.claims.sim %>% left_join(temp)
gross.claims.sim

# Predicted aggregated claims, which we use to determine premium and expenses
gross.summ <- gross.claims.sim %>%
  summarize(avg.gross.claims = mean(gross.claims)) %>% 
  mutate(
    gross.premium = avg.gross.claims * (1 + gross.load),
    expenses = avg.gross.claims * expense
    )
gross.summ

# Bringing the gross premium and expenses to the table, just for completeness
gross.claims.sim <- gross.claims.sim %>% 
  mutate(
    gross.premium = gross.summ$gross.premium,
    expenses = gross.summ$expenses
    )
gross.claims.sim

#################### Quota Share Reinsurance ########################

# Remind our assumptions: quota share reinsured (retention), ceding commission,
# loss corridor from claims ratio and loss corridor to claims ratio
retention
commission
lc.from.cr
lc.to.cr

# Extension of the loss corridor (auxiliary value, useful for calculations below)
lc.diff.cr <- lc.to.cr - lc.from.cr
lc.diff.cr

# Reinsurance premium and reinsurance commision, in €
quota.share.prem <- gross.summ$gross.premium * retention
quota.share.prem
quota.share.comm <- quota.share.prem * commission
quota.share.comm

# Computing quota share liabilities 
quota.share.sim <- gross.claims.sim %>%
  # Taking these values to the table, just for completeness
  mutate(
    quota.share.prem = quota.share.prem,
    quota.share.comm = quota.share.comm
  ) %>% 
  # Amount of claims for which the insurer is responsible (without loss corridor)
  mutate(quota.share.claims = gross.claims * retention) %>% 
  # Quota share's combined ratio (cr)
  mutate(
    # Quota share's combined ratio (cr)
    quota.share.cr = (quota.share.claims + quota.share.comm) / quota.share.prem,
  ) 
quota.share.sim

# Now the loss corridor 
quota.share.sim <- quota.share.sim %>% 
  # Loss corridor liability (proportion and €)
  mutate(
    # The loss corridor liability is zero unless the claims ratio is greater than the
    # "loss corridor from claims ratio".
    lc.liab.prop = if_else(
      quota.share.cr < lc.from.cr, 0, quota.share.cr - lc.from.cr
      )
  ) %>% 
  mutate(
    # The reinsured is 100% liable only up to the maximum extension of the loss corridor
    lc.liab.prop = if_else(lc.diff.cr < lc.liab.prop, lc.diff.cr, lc.liab.prop),
    lc.liab.euros = quota.share.prem * lc.liab.prop
  )
quota.share.sim %>% glimpse

# Final result of quota share for the reinsurer
quota.share.sim <- quota.share.sim %>% 
  mutate(
    result.qs.reins = quota.share.prem - quota.share.comm - quota.share.claims + lc.liab.euros
    )
quota.share.sim


############## Excess of Loss (XL) Reinsurance #################

# Remind our assumptions regarding Excess of Loss: XL priority, XL limit, Profit loading
priority
limit
loading

# Another assumption: retention after quota share
retention.XL <- 1 - retention
retention.XL

# First we compute the claims to the reinsurer under excess of loss.
claims.sim.severities <- claims.sim.severities %>% 
  mutate(
    # Retained severity of each claim after quota share
    retained.sev.XL = severity * retention.XL,
    XL.severity = case_when(
      retained.sev.XL < priority ~ 0,
      retained.sev.XL >= priority & retained.sev.XL <= limit ~ retained.sev.XL - priority,
      retained.sev.XL > limit ~ limit - priority
    )
  )

claims.sim.severities

# Aggregate the XL claims for each simulation
XL.sim <- claims.sim.severities %>% 
  group_by(sim) %>% 
  summarize(XL.claims = sum(XL.severity), .groups = "drop")
XL.sim

# The XL premium will be 125% of the expected claim loss (see assumptions)
avg.XL.claim.cost <- XL.sim %>% summarize(mean=mean(XL.claims)) %>% pull
avg.XL.claim.cost

XL.prem <- avg.XL.claim.cost * (1 + loading)
XL.prem

# Let us see the result of the XL reinsurer
XL.sim <- XL.sim %>%
  mutate(result.XL.reins = XL.prem - XL.claims)
XL.sim

############################# Net Result for Insurer ########################


final.result.sim <- gross.claims.sim %>% 
  mutate(
    # First, the gross results
    gross.result = gross.summ$gross.premium - gross.summ$expenses - gross.claims,
    ) 
final.result.sim

# Add quota share results
final.result.sim <- final.result.sim %>% 
  # Bring necessary data from quota share simulation
  left_join(quota.share.sim %>% select(sim, quota.share.claims, lc.liab.euros)) %>% 
  # The part of the claims that the reinsurer paid to the insurer are called  
  # "recoveries" in the insurer balance sheet
  rename(qs.recoveries = quota.share.claims) %>% 
  # Compute result from quota share for the insurer
  mutate(
    qs.ins.result = -quota.share.prem + quota.share.comm + qs.recoveries - lc.liab.euros
    )
final.result.sim

# Add excess of loss results
final.result.sim <- final.result.sim %>% 
  # Bring necessary data from XL simulation
  left_join(XL.sim %>% select(sim, XL.claims)) %>% 
  # The part of the claims that the reinsurer paid to the insurer are called  
  # "recoveries" in the insurer balance sheet
  rename(XL.recoveries = XL.claims) %>% 
  # compute result from XL for the insurer
  mutate(
    XL.ins.result = -XL.prem + XL.recoveries
  )
final.result.sim %>% glimpse

# Net result
final.result.sim <- final.result.sim %>% 
  mutate(
    net.result = gross.result + qs.ins.result + XL.ins.result,
    # net.result = gross.summ$gross.premium - gross.summ$expenses - gross.claims -
    #   quota.share.prem + quota.share.comm + qs.recoveries - lc.liab.euros -
    #   XL.prem + XL.recoveries
  )
final.result.sim

########################## Results mean and percentiles ########################

expected.results <- final.result.sim %>% 
  summarize(across(ends_with("result"), mean))
expected.results

quantiles <- seq(from = 0.01, to = 0.99, by = 0.01)
quantiles

perc.results <- final.result.sim %>% 
  reframe(
    quantile = quantiles,
    across(ends_with("result"), ~quantile(., probs = quantiles))
  )
perc.results

plot.table <- perc.results %>%
  select(quantile, gross.result, net.result) %>% 
  pivot_longer(cols = ends_with("result"), names_to = "Type")
plot.table

static.plot <- plot.table %>% 
  ggplot(aes(x = quantile, y = value, color = Type)) +
  geom_line() +
  labs(title = "Result for the primary insurer - gross and net of reinsurance") +
  scale_x_continuous() + 
  theme_bw()
static.plot

animated.plot <- ggplotly(static.plot)
animated.plot

########################## VaR and TailVaR of losses #########################

# In this section we compute the VaR and TailVaR of (simulated losses - expected losses)

# Gross loss (without any reinsurance) and net loss (with quota share and
# excess loss reinsurance)
final.result.sim <- final.result.sim %>% 
  mutate(
    gross.loss = -gross.result,
    net.loss = -net.result
      ) %>% 
  mutate(
    Loss.gross = gross.loss - mean(gross.loss),
    Loss.net = net.loss - mean(net.loss)
  )
final.result.sim

VaR <- final.result.sim %>% 
  # percentile (confidence level assumption "cl")
  summarize(
    VaR.gross = quantile(Loss.gross, probs = cl),
    VaR.net = quantile(Loss.net, probs = cl)
  )
VaR

# TailVaR of gross loss 
final.result.sim %>% 
  filter(Loss.gross > VaR$VaR.gross) %>% 
  summarize(mean(Loss.gross))

# TailVaR of net loss
final.result.sim %>% 
  filter(Loss.net > VaR$VaR.net) %>% 
  summarize(mean(Loss.net))

################### VaR vs TailVaR #############################

# In this section we compute the TailVaR of simulated losses for every percentile
# and plot it against the respective VaR

perc.losses <- final.result.sim %>% 
  reframe(
    quantile = quantiles,
    across(ends_with("loss"), ~quantile(., probs = quantiles))
  )
perc.losses

# Cycle for TailVaR computing (gross loss)

n <- nrow(perc.losses)
vector.tailvar <- vector(mode = "numeric", length = n)
for (i in seq_along(vector.tailvar)){
  
  VaR <- perc.losses %>% slice(i) %>% pull(gross.loss)
  
  vector.tailvar[[i]] <- final.result.sim %>%
    filter(gross.loss > VaR) %>%
    summarize(tailvar = mean(gross.loss))%>%
    pull(tailvar) 
  
}

vector.tailvar

perc.losses <- perc.losses %>% 
  mutate(gross.loss.tailvar = vector.tailvar)

# Cycle for TailVaR computing (net loss)

n <- nrow(perc.losses)
vector.tailvar <- vector(mode = "numeric", length = n)
for (i in seq_along(vector.tailvar)){
  
  VaR <- perc.losses %>% slice(i) %>% pull(net.loss)
  
  vector.tailvar[[i]] <- final.result.sim %>%
    filter(net.loss > VaR) %>%
    summarize(tailvar = mean(net.loss))%>%
    pull(tailvar) 
  
}

vector.tailvar

perc.losses <- perc.losses %>% 
  mutate(net.loss.tailvar = vector.tailvar)
perc.losses


plot.table.losses <- perc.losses %>% 
  select(
    quantile,
    net.loss.VaR = net.loss, # rename this column for the plot
    net.loss.tailvar,
    gross.loss.VaR = gross.loss, # also rename this one
    gross.loss.tailvar
    ) %>% 
  pivot_longer(cols = contains("loss"), names_to = "Type")
plot.table.losses

tailvar.net.loss.plot <- plot.table.losses %>% 
  ggplot(aes(x = quantile, y = value, color = Type)) +
  geom_line() +
  labs(title = "Net Loss - VaR vs. TailVaR") +
  theme_bw()
tailvar.net.loss.plot

ggplotly(tailvar.net.loss.plot)
